<?php
// +----------------------------------------------------------------------
// | 节流设置
// +----------------------------------------------------------------------
use think\middleware\Throttle;
use think\middleware\throttle\CounterSlider;
use think\Request;
use think\Response;
use sheep\exception\SheepException;

return [
    // 缓存键前缀，防止键值与其他应用冲突
    'prefix' => 'throttle_',
    // 不需要限流的 uri
    'no_throttle_uris' => [
        // 后端接口
        '/shop/admin/goods/goods/select',
        '/shop/admin/goods/goods/activitySelect',
        '/shop/admin/activity/activity/:id',
        '/shop/admin/order/order/dispatch',
        '/wechat/admin/user/checkScan',

        // 前端接口
        '/shop/api/goods/goods/ids',
        '/shop/api/goods/goods/activity',
    ],

    // 缓存的键，true 表示使用来源ip
    'key' => function(Throttle $throttle, Request $request) {
        if (is_throttle()) {
            // 接口独立使用限流
            return $request->ip() . '|' . $request->baseUrl() . '|' . $request->server('HTTP_USER_AGENT');
        } else {
            return md5(time() . mt_rand(1000, 9999));       // 随机生成一个不可能再重复的key
        }
    },
    // 要被限制的请求类型, eg: GET POST PUT DELETE HEAD 等
    'visit_method' => ['GET', 'POST', 'PUT', 'DELETE', 'HEAD'],
    // 设置访问频率，例如 '10/m' 指的是允许每分钟请求10次;'10/60'指允许每60秒请求10次。值 null 表示不限制， eg: null 10/m  20/h  300/d 200/300
    'visit_rate' => '40/m',
    /*
     * 设置节流算法，组件提供了四种算法：
     *  - CounterFixed ：计数固定窗口
     *  - CounterSlider: 滑动窗口
     *  - TokenBucket : 令牌桶算法
     *  - LeakyBucket : 漏桶限流算法
     */
    'driver_name' => CounterSlider::class,
    // 响应体中设置速率限制的头部信息，含义见：https://docs.github.com/en/rest/overview/resources-in-the-rest-api#rate-limiting
    'visit_enable_show_rate_limit' => true,
    // 访问受限时返回的响应
    'visit_fail_response' => function (Throttle $throttle, Request $request, int $wait_seconds) {
        throw (new SheepException)->setMessage('操作频繁, 请稍后重试', 1, 429);
        // return Response::create('Too many requests, try again after ' . $wait_seconds . ' seconds.')->code(429);
    },
];
